package com.elitel.frame.base.controller;

import com.elitel.frame.base.service.UserInfoService;
import com.elitel.frame.main.entity.ext.ExtUserInfo;
import com.elitel.frame.main.entity.vo.JsonResult;
import com.elitel.frame.main.entity.vo.PageRequestVo;
import com.elitel.frame.main.entity.vo.PageResponseVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;

/**
 * TODO: UserController
 *
 * @since 2020-02-18
 */
@RestController
@RequestMapping("/system/user")
public class UserController {

  private static final Logger logger = LoggerFactory.getLogger(UserController.class);
  @Autowired private BCryptPasswordEncoder bCryptPasswordEncoder;
  @Autowired private UserInfoService userInfoService;

  @Value("${authorize.default.password}")
  private String defaultPassword;

  /**
   * TODO: 添加用户
   *
   * @param extUserInfo
   * @return
   */
  @PostMapping("/addUser")
  public Object addUser(@RequestBody ExtUserInfo extUserInfo) {
    JsonResult jr = new JsonResult();
    try {
      ExtUserInfo userInfo = userInfoService.selectByLoginName(extUserInfo.getLoginname());
      if (userInfo != null) {
        jr.setSuccess(false);
        jr.setMsg(String.format("当前用户【%s】已存在！", extUserInfo.getLoginname()));
        return jr;
      }
      extUserInfo.setUserId(UUID.randomUUID().toString());
      extUserInfo.setAuthorizationCode(UUID.randomUUID().toString());
      extUserInfo.setPassword(bCryptPasswordEncoder.encode(defaultPassword));
      userInfoService.insertUserInfo(extUserInfo);
      jr.setSuccess(true);
      jr.setMsg("添加用户信息成功~，用户默认密码为：" + defaultPassword);
    } catch (Exception e) {
      jr.setSuccess(false);
      jr.setMsg("添加用户信息异常！");
      logger.error(e.getMessage(), e);
    }
    return jr;
  }

  /**
   * TODO: 更改用户
   *
   * @param extUserInfo
   * @return
   */
  @PostMapping("/updateUser")
  public Object updateUser(@RequestBody ExtUserInfo extUserInfo) {
    JsonResult jr = new JsonResult();
    try {
      userInfoService.updateUserInfo(extUserInfo, true);
      jr.setSuccess(true);
      jr.setMsg("更新用户信息成功！");
    } catch (Exception e) {
      jr.setSuccess(false);
      jr.setMsg("修改用户信息异常！");
      logger.error(e.getMessage(), e);
    }
    return jr;
  }

  /**
   * TODO: 删除用户
   *
   * @param loginname
   * @return
   */
  @RequestMapping("/deleteUser/{loginname}")
  public Object deleteUser(@PathVariable String loginname) {
    JsonResult jr = new JsonResult();
    try {
      userInfoService.deleteUserInfo(loginname);
      jr.setSuccess(true);
      jr.setMsg("删除用户信息成功！");
    } catch (Exception e) {
      jr.setSuccess(false);
      jr.setMsg("删除用户信息异常！");
      logger.error(e.getMessage(), e);
    }
    return jr;
  }

  /**
   * 获取用户列表
   *
   * @param pageNo
   * @param pageSize
   * @param seachTxt
   * @return
   */
  @RequestMapping("/getUserInfoList")
  public Object getUserInfoList(String pageNo, String pageSize, String seachTxt) {
    JsonResult jr = new JsonResult();
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    try {
      PageRequestVo<ExtUserInfo> pr = new PageRequestVo<ExtUserInfo>();
      pr.setSearchContent(seachTxt);
      pr.setPageNo(Integer.valueOf(pageNo));
      pr.setPageSize(Integer.valueOf(pageSize));
      pr.setLoginname(authentication.getName());
      PageResponseVo<ExtUserInfo> pagelist = userInfoService.getUserInfoList(pr);
      jr.setData(pagelist);
      jr.setSuccess(true);
    } catch (Exception e) {
      jr.setSuccess(false);
      jr.setMsg("用户列表加载异常！");
      logger.error(e.getMessage(), e);
    }
    return jr;
  }

  /**
   * 根据 userID 获取用户信息
   *
   * @param userId
   * @return
   */
  @RequestMapping("/getUserInfoByUserId/{userId}")
  public Object getUserInfoByUserId(@PathVariable String userId) {
    JsonResult jr = new JsonResult();
    try {
      jr.setSuccess(true);
      ExtUserInfo userInfo = userInfoService.selectByUserId(userId);
      jr.setData(userInfo);
    } catch (Exception e) {
      jr.setSuccess(false);
      jr.setMsg("用户详情加载异常！");
      logger.error(e.getMessage(), e);
    }
    return jr;
  }

  /**
   * TODO: 重置指定信息
   *
   * @param extUserInfo
   * @return
   */
  @PostMapping("/resetUserInfo")
  public Object resetUserInfo(@RequestBody ExtUserInfo extUserInfo) {
    JsonResult jr = new JsonResult();
    try {
      if (extUserInfo.getMark().equalsIgnoreCase("password")) {
        // 判断用户是否输入密码
        if ("".equals(extUserInfo.getPassword()) || extUserInfo.getPassword() == null) {
          extUserInfo.setPassword(bCryptPasswordEncoder.encode(defaultPassword));
          jr.setMsg("用户默认密码为：" + defaultPassword);
        } else {
          Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
          ExtUserInfo userInfo = userInfoService.selectByLoginName(authentication.getName());
          // 判断原密码是否匹配
          if (userInfo == null
              || !bCryptPasswordEncoder.matches(
                  extUserInfo.getPassword(), userInfo.getPassword())) {
            jr.setSuccess(false);
            jr.setMsg("原密码不匹配");
            return jr;
          }
          String newPassword = bCryptPasswordEncoder.encode(extUserInfo.getNewPassword());
          // 设置新密码
          extUserInfo = userInfo;
          extUserInfo.setPassword(newPassword);
        }
      }

      if (extUserInfo.getMark() != null
          && extUserInfo.getMark().equalsIgnoreCase("authorizationCode")) {
        extUserInfo.setAuthorizationCode(UUID.randomUUID().toString());
      }
      userInfoService.updateUserInfo(extUserInfo, false);
      jr.setSuccess(true);
    } catch (Exception e) {
      jr.setSuccess(false);
      jr.setMsg(e.getMessage());
      logger.error(e.getMessage(), e);
    }
    return jr;
  }

}
